package com.groupbuying.storeinternal.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * @anthor wenguoqiang
 * @date: 2019/02/21 17:24
 * @company 够样
 * @des
 **/
public class MultipartFileUtils {

    public static MultipartFile transferMultipartFile(File file){

        MultipartFile mulFile = null;
        try {
            FileItem fileItem = new DiskFileItem("files", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile());
            InputStream input = new FileInputStream(file);
            OutputStream os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            mulFile = new CommonsMultipartFile(fileItem);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mulFile;
    }

    public static MultipartFile[] transferMultipartFiles(List<File> files){
        List <MultipartFile> multipartFileList = new ArrayList<MultipartFile>();
        for(File file : files){
            multipartFileList.add(transferMultipartFile(file));
        }
        MultipartFile[] multipartFiles = new  MultipartFile[multipartFileList.size()] ;
        return multipartFileList.toArray(multipartFiles);

    }

}
